- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathCoinCombinations.java
44 lines (32 loc) Β· 837 Bytes
/
CoinCombinations.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
packagesection12_Backtracking;
publicclassCoinCombinations {
staticintcount = 0;
publicstaticvoidmain(String[] args) {
int[] denominations = { 2, 3, 5, 6 };
intamount = 10;
Stringans = "";
intcurrentSum = 0;
intlastCoinIdx = 0;
coinCombinations(denominations, amount, ans, currentSum, lastCoinIdx);
}
staticvoidcoinCombinations(int[] coins, intamount, Stringans, intcurrentSum, intlastCoinIdx) {
if (currentSum == amount) {
count++;
System.out.println(count + ". " + ans);
return;
}
if (currentSum > amount) {
return;
}
for (intcurrentCoin = lastCoinIdx; currentCoin < coins.length; currentCoin++) {
coinCombinations(coins, amount, ans + coins[currentCoin], currentSum + coins[currentCoin], currentCoin);
}
}
}
/*output
1. 22222
2. 2233
3. 226
4. 235
5. 55
*/